#pragma once
#include<iostream>
#include<string>
#include<memory>
#include<functional>
#include<unistd.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include"Protocol.hpp"
//封装文件描述符
class EpollServer;
class Connection {//链接基类
    public:
        Connection()
        {}
        
        void CallRead()
        {
            _read_callback();
        }
        void CallWrite()
        {
            _write_callback();
        }
        void CallExcept()
        {
            _except_callback();
        }

        int GetFd()
        {
            return _sock_fd;
        }
        void SetFd(int fd)
        {
            _sock_fd = fd;
        }
      
        uint32_t GetEvents()
        {
            return _events;
        }
        void SetEvents(uint32_t events)
        {
            _events = events;
        }
        
        EpollServer* GetEpollOwner()
        {
            return _epoll_owner;
        }
        void SetEpollOwner(EpollServer *epoll_owner)//设置所属的epollServer
        {
            _epoll_owner = epoll_owner;
        }

        void Append2Inbuffer(const std::string &in_data)//便于read操作，读全
        {
            _inbuffer+=in_data;//把收到的数据添加到自己的接收缓冲区
        }

        void Append2Outbuffer(const std::string &out_data)//便于write操作
        {
            _outbuffer+=out_data;//把要发送的数据添加到自己的发送缓冲区
        }
        std::string Test()
        {
            return _inbuffer;
        }

        void Close()
        {
            if(_sock_fd >= 0)
                close(_sock_fd);
        }
        ~Connection(){}
        
        std::string& GetInbuffer()
        {
            return _inbuffer;
        }
        void SetHandleMessage(func_t handle_message)//设置处理消息的回调函数
        {
            _HandleMessage = handle_message;
        }
    public:
        //回调方法
        virtual void _read_callback() = 0;//读事件回调
        virtual void _write_callback() = 0;//写事件回调
        virtual void _except_callback() = 0;//异常事件回调
    protected:
        bool IsWriteEmpty()//判断发送缓冲区是否为空
        {
            return _outbuffer.empty();
        }
        void SplitOutbuffer(int n)//以滑动窗口式裁剪发送缓冲区
        {
            _outbuffer.erase(0,n);
        }
    protected:
        int _sock_fd = -1;
        uint32_t _events = 0;//connection关心 的事件
        struct sockaddr_in _client;//客户端地址信息

        std::string _inbuffer;//接收缓冲区
        std::string _outbuffer;//发送缓冲区
        EpollServer *_epoll_owner;//所属的epollServer

        func_t _HandleMessage;//处理消息的回调函数

};



